import React, { PureComponent, Fragment } from 'react';
import { Map, Markers } from 'react-amap';
import { connect } from 'dva';
import { Row, Col, Card, Select, message, Input, Icon } from 'antd';
import NumberInfo from 'components/NumberInfo';
import Authorized from '../../utils/Authorized';
import styles from './Monitor.less';
import caron from '../../assets/carOnline.png';

import caroff from '../../assets/caroff.png';
import MyInfoWindow from '../../components/GDMap/MyInfoWindow';
import Geolocation from '../../components/GDMap/Geolocation';
import Autocomplete from '../../components/GDMap/Autocomplete';
import { citys } from '../../utils/city';
import {
  setCity,
  getCity,
  getIntervalFreshText,
  setIntervalFreshText,
  getIntervalFreshValue,
  setIntervalFreshValue,
} from '../../utils/authority';

const { Secured } = Authorized;
const { Search } = Input;
const gridStyle = {
  width: '20%',
  textAlign: 'center',
  height: 74,
};
// // use permission as a parameter
// const havePermissionAsync = new Promise(resolve => {
//   // Call resolve on behalf of passed
//   setTimeout(() => resolve(), 1000);
// });
// @Secured(havePermissionAsync)
@connect(({ monitor, loading }) => ({
  monitor,
  loading: loading.models.monitor,
}))
export default class Monitor extends PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      position: {
        longitude: 114.085947,
        latitude: 22.547,
      },
      markers: [],
      isClick: false,
      city: '',
      height: 0,
      filter: '',
      intervalFresh: 10000,
    };
    this.markersEvents = {
      click: (e, marker) => {
        // 通过高德原生提供的 getExtData 方法获取原始数据
        const extData = marker.getExtData();
        // console.log('marker pressed', this.state.isClick, extData);
        this.props.dispatch({
          type: 'monitor/fetchmarkerinfo',
          payload: { devId: extData.devId },
        });
        this.setState({ position: extData.position });
        this.setState({ isClick: true });
      },
    };
    this.windowEvents = {
      close: () => {
        this.setState({ isClick: false });
      },
    };
  }

  componentDidMount() {
    // const height = this.divElement.clientHeight;
    // //console.log('table height', height);
    // this.setState({ height });
    const sessionCity = getCity();
    if (sessionCity !== '初始值') {
      // 已有用户选择的城市
      const { city, position } = JSON.parse(sessionCity);
      console.log('session city', city, position);
      //this.setState({ city: sessionCity, position: citys[sessionCity] });
      this.setState({ city, position });
      this.props.dispatch({
        type: 'monitor/fetchCity',
        payload: {},
        callback: cityarray => {
          console.log('city array', cityarray);
        },
      });
    } else {
      this.props.dispatch({
        type: 'monitor/fetchCity',
        payload: {},
        callback: cityarray => {
          this.handleChange(cityarray[0].name);
        },
      });
    }

    const freshValue = getIntervalFreshValue();
    if (freshValue !== '手动') {
      if (!this.timer || this.timer === null) {
        this.timer = setInterval(() => {
          this.props.dispatch({
            type: 'monitor/fetchTags',
            payload: { onOffLine: 1 },
          });
        }, getIntervalFreshValue());
      }
    }

    this.props.dispatch({
      type: 'monitor/fetchTags',
      payload: { onOffLine: 1 },
    });

    //console.log('this.props.location', this.props.location);
    if (this.props.location ?.state ?.devId) {
      this.setState({ filter: this.props.location.state.devId });
    }
    this.forceUpdate();
  }

  componentWillUnmount() {
    clearInterval(this.timer);
  }

  onLocationError = () => {
    message.info('定位失败.');
    this.props.dispatch({
      type: 'monitor/fetchTags',
      payload: { onOffLine: 1 },
    });
  };

  getMarkerTest = GeolocationResult => {
    console.log('GeolocationResult', GeolocationResult);
  };
  getMarker = GeolocationResult => {
    // console.log('GeolocationResult', GeolocationResult);
    const location = GeolocationResult.addressComponent;
    if (location && Object.keys(citys).indexOf(location.city) > -1) {
      // 定位的城市属于 支持城市
      const sessionCity = getCity();
      console.log('sessionCity 支持定位', sessionCity);
      if (sessionCity !== '初始值' && sessionCity !== location.city) {
        // 已有选择的城市 且用户选择城市不等于定位城市  优先用户选择
        // console.log('session city', sessionCity, citys[sessionCity]);
        const { city, position } = sessionCity;
        this.setState({ city, position });
      } else {
        // console.log('find city', location.city, citys[location.city]);
        this.setState({
          city: location.city,
          position: {
            longitude: GeolocationResult.position.lng,
            latitude: GeolocationResult.position.lat,
          },
        });
        // console.log('after set', this.state.city, this.state.position);
        setCity({
          city: location.city,
          position: {
            longitude: GeolocationResult.position.lng,
            latitude: GeolocationResult.position.lat,
          },
        });
      }
    } else {
      // 定位的城市 系统不支持
      const sessionCity = getCity();
      if (sessionCity !== '初始值') {
        // 已有用户选择的城市

        //console.log('sessionCity 不支持定位', sessionCity);
        const { city, position } = sessionCity;
        this.setState({ city, position });
      } else {
        message.info('暂不支持您所在的城市，自动跳转到上海市');
      }
    }
    // this.props.dispatch({
    //   type: 'monitor/fetchTags',
    // });
    // this.forceUpdate();
  };

  handleChange = value => {
    //console.log('city value', value);
    const { monitor } = this.props;
    let { cityList } = monitor;
    const city = cityList.find(item => item.name === value);
    if (city != null) {
      const { name, lngLat } = city;
      const longitude = lngLat.split(';')[0];
      const latitude = lngLat.split(';')[1];
      this.setState({
        city: name,
        position: {
          longitude,
          latitude,
        },
        isClick: false,
      });
      setCity(
        JSON.stringify({
          city: name,
          position: {
            longitude,
            latitude,
          },
        })
      );
      // console.log('getCity', getCity());
      this.props.dispatch({
        type: 'monitor/fetchTags',
        payload: { onOffLine: 1 },
      });
    }
  };

  handleIntervalFreshTimeChange = value => {
    clearInterval(this.timer);
    //  this.setState({ intervalFresh: parseInt(value, 10) });

    if (value === '10000') {
      setIntervalFreshText('10秒');
    } else if (value === '30000') {
      setIntervalFreshText('30秒');
    } else if (value === '60000') {
      setIntervalFreshText('60秒');
    } else if (value === '300000') {
      setIntervalFreshText('5分钟');
    } else if (value === '600000') {
      setIntervalFreshText('10分钟');
    } else if (value === '手动') {
      setIntervalFreshText('手动');
    }

    if (value !== '手动') {
      this.timer = setInterval(() => {
        this.props.dispatch({
          type: 'monitor/fetchTags',
          payload: { onOffLine: 1 },
        });
      }, value);
    }
    this.forceUpdate();
  };

  renderIcon = extData => {
    if (extData.onOffline === 0) return <img src={caroff} className={styles.Appicon} alt="car" />;
    else return <img src={caron} className={styles.Appicon} alt="caron" />;
  };
  filterTags = item => {
    const itemValues = Object.values(item);
    for (const i of itemValues.values()) {
      // console.log('i,this.filter', i, this.filter)
      if (typeof i === 'string' && i.includes(this.state.filter)) {
        return 1;
      }
    }
    return 0;
  };
  selectfunc = e => {
    //console.log('e', e);
    if (e.poi.location) {
      this.setState({ position: { longitude: e.poi.location.lng, latitude: e.poi.location.lat } });
    }
  };
  render() {
    const { monitor } = this.props;
    let { tags, devNum, onDevNum, weekOffDevNum, yearOffDevNum, devinfo, cityList, vehCount, progDevNum, todayVehCount } = monitor;
    if (this.state.filter) {
      tags = tags.filter(this.filterTags);
    }
    const pluginProps = {
      enableHighAccuracy: true,
      timeout: 10000,
      showButton: true,
      panToLocation: false,
    };

    const searchProps = {};
    const mapPlugins = [
      'Scale',
      'OverView',
      'ControlBar', // v1.1.0 新增
    ];
    const style = { position: 'absolute', left: 5, top: 5 };
    const Option = Select.Option;
    const extraButton = (
      <Row>
        <Col>
          <Select value={this.state.city} style={{ width: 120 }} onChange={this.handleChange}>
            {cityList
              ? cityList.map(item => (
                <Option key="name" value={item.name}>
                  {item.name}
                </Option>
              ))
              : null}
          </Select>
        </Col>
        <Col>
          <Search
            placeholder="输入车辆信息"
            enterButton="查询"
            size="large"
            onSearch={value => this.setState({ filter: value })}
          />
        </Col>
      </Row>
    );
    return (
      <Fragment>
        <Row gutter={24} className={styles.mapRow}>
          <Col xl={24} lg={24} md={24} sm={24} xs={24} className={styles.mapCol}>
            <Card title="设备实时监控" bordered={false} className={styles.card}>
              <Row>
                <Card.Grid style={gridStyle}>
                  <Icon type="environment" theme="twoTone" className={styles.icon} twoToneColor='red' />
                  设备总数：<span className={styles.totalText}>{devNum}</span>台
                </Card.Grid>
                <Card.Grid style={gridStyle}>
                  <Icon type="cloud" theme="twoTone" className={styles.icon} twoToneColor='blue' />
                  在线设备数：<span className={styles.onLineText}>{onDevNum}</span>台
                </Card.Grid>
                <Card.Grid style={gridStyle}>
                  <Icon type="car" theme="twoTone" className={styles.icon} twoToneColor='green' />
                  车辆总数：<span className={styles.carText}>{vehCount}</span>辆

                </Card.Grid>
                <Card.Grid style={gridStyle}>
                  <Icon type="picture" theme="twoTone" className={styles.icon} twoToneColor='orange' />
                  已发节目设备数：<span className={styles.proText}>{progDevNum}</span>台
                </Card.Grid>
                <Card.Grid style={gridStyle}>
                  <Icon type="notification" theme="twoTone" className={styles.icon} twoToneColor='gray' />
                  今日投放车辆数：<span className={styles.playText}>{todayVehCount}</span>辆
                </Card.Grid>

              </Row>
              <Row className={styles.searchRow}>
                <Col span={4}>
                  选择城市：
                  <Select value={this.state.city} style={{ width: 120 }} onChange={this.handleChange}>
                    {cityList
                      ? cityList.map(item => (
                        <Option key="name" value={item.name}>
                          {item.name}
                        </Option>
                      ))
                      : null}
                  </Select>
                </Col>
                <Col span={4}>
                  刷新频率：
                <Select
                    value={getIntervalFreshText()}
                    style={{ width: 120 }}
                    onChange={this.handleIntervalFreshTimeChange}
                  >
                    <Option value="10000">10秒</Option>
                    <Option value="30000">30秒</Option>
                    <Option value="60000">60秒</Option>
                    <Option value="300000">5分钟</Option>
                    <Option value="600000">10分钟</Option>
                    <Option value="手动">手动</Option>
                  </Select>
                </Col>
                <Col span={6} offset={10}>
                  <Search
                    placeholder="输入车辆信息"
                    enterButton="查询"

                    onSearch={value => this.setState({ filter: value })}
                  />
                </Col>
              </Row>
              <div
                className={styles.mapChart}
                ref={divElement => {
                  this.divElement = divElement;
                }}
              >
                <Map
                  center={this.state.position}
                  zoom="10"
                  amapkey="74532947bf4c342a9f6e1546fe02325f"
                  plugins={mapPlugins}
                >
                  <Autocomplete
                    options={searchProps}
                    onSelect={e => this.selectfunc(e)}
                    style={style}
                    placeholder="地址查询"
                  />
                  <Markers markers={tags} render={this.renderIcon} events={this.markersEvents} />
                  <MyInfoWindow
                    devinfo={devinfo}
                    position={this.state.position}
                    visible={this.state.isClick}
                    events={this.windowEvents}
                    autoMove
                  />
                  <Geolocation
                    {...pluginProps}
                    onOk={this.getMarkerTest}
                    onError={this.onLocationError}
                  />
                </Map>
              </div>
            </Card>
          </Col>
          {/* <Col xl={6} lg={24} md={24} sm={24} xs={24} className={styles.mapCol}>
            <Card title="设备列表" className={styles.card} bordered={false}>
              <SimpleTable data={tags} height={this.state.height} />
            </Card>
          </Col> */}
        </Row>
      </Fragment >
    );
  }
}
